package com.example.service;

import com.example.entity.Coupon;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Service
public class MockCouponService {
    
    private final Map<Long, Coupon> mockDatabase = new HashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public MockCouponService() {
        // 初始化一些模拟数据
        initMockData();
    }
    
    private void initMockData() {
        createCoupon("满10减五", 1);
        createCoupon("满20减十", 1);
        createCoupon("满30减十五", 0);
    }
    
    // 获取所有优惠券
    public List<Coupon> getAllCoupons() {
        return new ArrayList<>(mockDatabase.values());
    }
    
    // 根据ID获取优惠券
    public Optional<Coupon> getCouponById(Long id) {
        return Optional.ofNullable(mockDatabase.get(id));
    }
    
    // 根据名称搜索优惠券
    public List<Coupon> searchCouponsByName(String name) {
        return mockDatabase.values().stream()
                .filter(coupon -> coupon.getCouponName().contains(name))
                .collect(Collectors.toList());
    }
    
    // 根据状态获取优惠券
    public List<Coupon> getCouponsByStatus(Integer status) {
        return mockDatabase.values().stream()
                .filter(coupon -> coupon.getCouponStatus().equals(status))
                .collect(Collectors.toList());
    }
    
    // 获取所有有效优惠券
    public List<Coupon> getActiveCoupons() {
        return getCouponsByStatus(1);
    }
    
    // 创建新优惠券
    public Coupon createCoupon(String name, Integer status) {
        Long id = idGenerator.getAndIncrement();
        Coupon coupon = new Coupon(name, status);
        coupon.setCouponId(id);
        mockDatabase.put(id, coupon);
        return coupon;
    }
    
    // 更新优惠券
    public Coupon updateCoupon(Long id, String name, Integer status) {
        Coupon coupon = mockDatabase.get(id);
        if (coupon != null) {
            if (name != null) {
                coupon.setCouponName(name);
            }
            if (status != null) {
                coupon.setCouponStatus(status);
            }
            mockDatabase.put(id, coupon);
        }
        return coupon;
    }
    
    // 删除优惠券
    public boolean deleteCoupon(Long id) {
        return mockDatabase.remove(id) != null;
    }
    
    // 批量删除优惠券
    public void deleteCoupons(List<Long> ids) {
        ids.forEach(mockDatabase::remove);
    }
    
    // 统计优惠券数量
    public long countCoupons() {
        return mockDatabase.size();
    }
    
    // 统计指定状态的优惠券数量
    public long countCouponsByStatus(Integer status) {
        return mockDatabase.values().stream()
                .filter(coupon -> coupon.getCouponStatus().equals(status))
                .count();
    }
}
